<template>
  <el-dialog
    :title="type === 'add' ? '新增目标' : '修改目标'"
    :visible.sync="dialogFormVisible"
    @closed="closed"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="dialogForm"
      label-position="right"
      label-width="100px"
    >
      <el-form-item label="识别码：" prop="targetNumber">
        <el-input
          @blur="identify"
          @change="targetNumberChangeHandle"
          placeholder="请输入识别码"
          v-model.trim="form.targetNumber"
        ></el-input>
      </el-form-item>
      <el-form-item label="目标名称：" prop="targetName">
        <el-input
          :disabled="true"
          placeholder="自动带入目标名称"
          v-model.trim="form.targetName"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="目标类型：" prop="targetType">
        <el-input
          :disabled="true"
          placeholder="自动带入目标类型"
          v-model.trim="form.targetType"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="经度：" prop="longitude">
        <el-input
          @blur="identifyArea"
          placeholder="东经为正，西经为负，小数点后保留6位"
          v-model.trim="form.longitude"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="纬度：" prop="latitude">
        <el-input
          @blur="identifyArea"
          placeholder="北纬为正，南纬为负，小数点后保留6位"
          v-model.trim="form.latitude"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="地区信息：" prop="areaIds">
        <el-cascader
          :props="{}"
          ref="checkArea"
          :options="options"
          v-model="form.areaIds"
          @change="handleChange"
        >
        </el-cascader>
      </el-form-item>
      <el-form-item label="图标：" prop="targetIcon">
        <el-radio-group v-model="form.targetIcon">
          <el-radio label="blue"
            ><img src="@/assets/map/blue.png" alt=""
          /></el-radio>
          <el-radio label="green"
            ><img src="@/assets/map/green.png" alt=""
          /></el-radio>
          <el-radio label="orange"
            ><img src="@/assets/map/orange.png" alt=""
          /></el-radio>
          <el-radio label="purple"
            ><img src="@/assets/map/purple.png" alt=""
          /></el-radio>
          <el-radio label="skyblue"
            ><img src="@/assets/map/skyblue.png" alt=""
          /></el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { regionData } from "element-china-area-data";
export default {
  name: "AddDialog",
  data() {
    var validateLng = (rule, value, callback) => {
      if (typeof +value != "number" || Math.abs(+value) > 180) {
        callback(new Error("请输入正确格式的经度"));
      }
      var reg =
        /^([-+]?((1[0-7][0-9]|[1-9]?[0-9])(\.\d{1,6})?|180(\.0{1,6})?))$/;
      var result = reg.test(value);
      if (!result) {
        callback(new Error("请输入正确格式的经度"));
      } else {
        callback();
      }
    };
    var validateLat = (rule, value, callback) => {
      if (typeof +value != "number" || Math.abs(+value) > 90) {
        callback(new Error("请输入正确格式的纬度"));
      }
      var reg = /^([-+]?([1-8]?[0-9](\.\d{1,6})?|90(\.0{1,6})?))$/;
      var result = reg.test(value);
      if (!result) {
        callback(new Error("请输入正确格式的纬度"));
      } else {
        callback();
      }
    };
    return {
      type: null,
      targetId: null,
      dialogFormVisible: false,
      options: [],
      form: {
        entityId: null,
        targetNumber: null,
        targetName: null,
        targetType: null,
        targetTypeId: null,
        longitude: null,
        latitude: null,
        areaInfo: null,
        areaIds: null,
        targetIcon: null,
      },
      rules: {
        targetNumber: [
          {
            required: true,
            message: "请输入识别码",
            trigger: "blur",
          },
        ],
        /* targetName: [
          {
            required: true,
            message: "请输入目标名称",
            trigger: "blur",
          },
        ],
        targetType: [
          {
            required: true,
            message: "请输入目标类型",
            trigger: "blur",
          },
        ], */
        longitude: [
          { validator: validateLng, required: true, trigger: "blur" },
        ],
        latitude: [{ validator: validateLat, required: true, trigger: "blur" }],
        areaIds: [
          {
            required: true,
            message: "请选择地区信息",
            trigger: "blur",
          },
        ],
        targetIcon: [
          {
            required: true,
            message: "请选择图标",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    // this.init();
  },
  mounted() {
    const taiwan = require("../utils/taiwan.json");
    let areaData = [
      {
        label: "中国",
        value: "0",
        children: regionData,
      },
    ];
    areaData[0].children.forEach((item) => {
      if (item.label === "台湾省") {
        item.children = taiwan.children;
      }
    });
    this.options = areaData;
  },
  methods: {
    open(type, targetId = null) {
      this.type = type;
      this.targetId = targetId;
      this.dialogFormVisible = true;
      this.init();
    },
    init() {
      console.log("弹框属性", this.type);
      if (this.type === "edit") {
        this.getTargetDetail();
      }
    },
    getTargetDetail() {
      this.$axios
        .get(this.$api.situationInfo.getTargetInfo + `/${this.targetId}`)
        .then((res) => {
          console.log("@获取目标详情", res);
          this.form.targetNumber = res.data.data.targetNumber;
          this.form.targetName = res.data.data.targetName;
          this.form.targetType = res.data.data.targetType;
          this.form.latitude = res.data.data.latitude;
          this.form.longitude = res.data.data.longitude;
          this.form.targetIcon = res.data.data.targetIcon;
          this.form.entityId = res.data.data.entityId;
          const areaObj = this.handleArea(res.data.data);
          this.form.areaIds = areaObj.areaIds;
          this.form.areaInfo = areaObj.areaInfo;
        })
        .catch((err) => {
          this.$message.error(err);
        });
    },
    handleArea(data) {
      let areaIds = ["0"];
      let areaInfo = ["中国"];
      this.options[0].children.forEach((item1) => {
        if (data.province == item1.label) {
          areaIds.push(item1.value);
          areaInfo.push(item1.label);
          item1.children.forEach((item2) => {
            if (data.city == item2.label) {
              areaIds.push(item2.value);
              areaInfo.push(item2.label);
              item2.children.forEach((item3) => {
                if (data.area == item3.label) {
                  areaIds.push(item3.value);
                  areaInfo.push(item3.label);
                }
              });
            }
          });
        }
      });
      return {
        areaIds,
        areaInfo,
      };
    },
    handleChange(ids) {
      console.log(ids);
      if (ids.length != 0) {
        let strArr = this.$refs["checkArea"].getCheckedNodes()[0].pathLabels;
        console.log(strArr);
        this.form.areaInfo = strArr;
      }
    },
    targetNumberChangeHandle() {
      this.form.targetName = "";
      this.form.targetType = "";
      this.form.targetTypeId = "";
      this.form.entityId = "";
    },
    cancel() {
      this.dialogFormVisible = false;
    },
    closed() {
      this.$refs.dialogForm.resetFields();
      this.form.areaInfo = [];
      this.form.areaIds = [];
    },
    identify() {
      if (!this.form.targetNumber) return;
      this.$axios
        .get(
          this.$api.situationInfo.getTargetNameAndTypeByCode +
            `/${this.$parent.curProject}/${this.form.targetNumber}`
        )
        .then((res) => {
          if (res.data.code === 500) {
            return;
          }
          // console.log("@识别", res);
          this.form.targetName = res.data.data.targetName;
          this.form.targetType = res.data.data.targetType;
          this.form.targetTypeId = res.data.data.targetTypeId;
          this.form.entityId = res.data.data.entityId;
        });
    },
    submit() {
      this.$refs.dialogForm.validate((valid) => {
        if (!valid) return;
        if (this.type === "add") {
          this.$axios
            .post(this.$api.situationInfo.addTargetInfo, {
              projectId: this.$parent.curProject,
              entityId: this.form.entityId,
              targetNumber: this.form.targetNumber,
              targetName: this.form.targetName,
              targetType: this.form.targetType,
              targetTypeId: this.form.targetTypeId,
              longitude: this.form.longitude,
              latitude: this.form.latitude,
              country: "中国",
              province: this.form.areaInfo[1],
              city: this.form.areaInfo[2],
              area: this.form.areaInfo[3],
              targetIcon: this.form.targetIcon,
            })
            .then((res) => {
              // console.log("@新增", res);
              if (res.data.code === 200) {
                this.$message.success(res.data.message);
                this.dialogFormVisible = false;
                this.$refs.dialogForm.resetFields();
                this.$emit("operateCompleted");
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch((err) => {
              this.$message.error(err);
            });
        } else {
          this.$axios
            .post(this.$api.situationInfo.updateTargetInfo, {
              projectId: this.$parent.curProject,
              targetId: this.targetId,
              entityId: this.form.entityId,
              targetNumber: this.form.targetNumber,
              targetName: this.form.targetName,
              targetType: this.form.targetType,
              targetTypeId: this.form.targetTypeId,
              longitude: this.form.longitude,
              latitude: this.form.latitude,
              country: "中国",
              province: this.form.areaInfo[1],
              city: this.form.areaInfo[2],
              area: this.form.areaInfo[3],
              targetIcon: this.form.targetIcon,
            })
            .then((res) => {
              // console.log("@修改", res);
              if (res.data.code === 200) {
                this.$message.success(res.data.message);
                this.dialogFormVisible = false;
                this.$refs.dialogForm.resetFields();
                this.$emit("operateCompleted");
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch((err) => {
              this.$message.error(err);
            });
        }
      });
    },
    identifyArea() {
      if (!this.form.latitude || !this.form.longitude) return;
      this.getAreaByLocation();
    },
    async getAreaByLocation() {
      const res = await this.$axios.post(
        this.$api.situationInfo.getAreaByLocation,
        {
          latitude: +this.form.latitude,
          longitude: +this.form.longitude,
        }
      );
      console.log("@根据经纬度获取地区信息", res);
      const areaObj = this.handleArea(res.data.data);
      this.form.areaIds = areaObj.areaIds;
      this.form.areaInfo = areaObj.areaInfo;
    },
  },
};
</script>

<style lang="scss" scoped>
.el-form-item {
  margin-bottom: 0;
}
/deep/ .el-dialog {
  width: 500px;
  border-radius: 5px;

  .el-dialog__body {
    padding: 0 30px;
    border-top: 1px solid $gray-400;
  }
  .el-dialog__footer {
    padding: 0 30px;
    padding-bottom: 20px;
  }
}

.el-form-item {
  margin: 20px 0;
  .el-select,
  .el-cascader {
    width: 100%;
  }
}

.el-radio {
  display: inline-flex;
  align-items: center;
}
</style>
